/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) Roman Divotkey, 2010-2011

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.logging;

import java.io.PrintStream;

import org.cogaen.core.Core;
import org.cogaen.core.Service;

/**
 * Logging system supporting Syslog compatible logging messages.
 * <p>
 * Each logging message is assigned one of the flowing priorities:
 * 
 * <ul>
 *   <li>Debug</li>
 *   <li>Info</li>
 *   <li>Notice</li>
 *   <li>Warning</li>
 *   <li>Error</li>
 *   <li>Critical</li>
 *   <li>Alert</li>
 *   <li>Emergency</li>
 * </ul>
 * </p>
 * 
 * @see <a href="http://en.wikipedia.org/wiki/Syslog">Syslog</a>
 */
public class LoggingService implements Service {

	/** Unique name of this service. */	
	public static final String NAME = "cogaen.loggingservice";
	
	public static final int DEBUG 		= 7;
	public static final int INFO 		= 6;
	public static final int NOTICE 		= 5;
	public static final int WARNING 	= 4;
	public static final int ERROR 		= 3;
	public static final int CRITICAL 	= 2;
	public static final int ALERT 		= 1;
	public static final int EMERGENCY 	= 0;
	
	private Core core;	
	private PrintStream ps;
	private int level;

	/**
	 * Returns the installed instance of this service.
	 * 
	 * <p>This is a convenience method. A call to this method is identical
	 * to the following code:
	 * <pre>
	 * (LoggingService) core.getService( LoggingService.NAME );
	 * </pre>
	 * </p>
	 * 
	 * @param core reference to a instance of core.
	 * @return installed service instance.
	 */
	public static LoggingService getInstance(Core core) {
		return (LoggingService) core.getService(NAME);
	}

	/**
	 * Creates a new instance of this class.
	 * 
	 * @param level logging level to be initialy set.
	 */
	public LoggingService(int level) {
		this.level = level;
		this.ps = System.err;
	}

	/**
	 * Creates a new instance of this class.
	 * 
	 * <p>The initial logging level is set to <strong>Warning</strong>.
	 */
	public LoggingService() {
		this(WARNING);
	}
	
	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public void initialize(Core core) {
		this.core = core;
	}
	
	/**
	 * Returns the current logging level.
	 * 
	 * @return the current logging level.
	 */
	public int getLevel() {
		return this.level;
	}
	

	/**
	 * Sets the current logging level.
	 * <p>Messages that have a lower priority compared to the current logging
	 * level are suppressed.
	 * </p>
	 * 
	 * @param level
	 * @throws IllegalArgumentException if specified level is not one of the predefined priority levels.
	 */
	public void setLevel(int level) {
		if (level < EMERGENCY || level > DEBUG) {
			throw new IllegalArgumentException("invalid logging level: " + level);
		}
		this.level = level;
	}
	
	private String levelToText(int level) {
		switch (level) {
		case DEBUG: return "DEBUG";
		case INFO: return "INFO";
		case NOTICE: return "NOTICE";
		case WARNING: return "WARNING";
		case ERROR: return "ERROR";
		case CRITICAL: return "CRITICAL";
		case ALERT: return "ALERT";
		case EMERGENCY: return "EMERGENCY";
		}
		
		throw new RuntimeException("illegal logging level");
	}
	
	private String timeToString(double time) {
		double t = time;
		int hours = (int) (t / 3600);
		t = t - hours * 3600;
		int minutes = (int) (t / 60);
		t = t - minutes * 60;
		int seconds = (int) t;
		t = t - seconds;
		int milliseconds = (int) (t * 1000);
		
		StringBuffer strbuf = new StringBuffer();
		if (hours < 10) {
			strbuf.append('0');
		}
		strbuf.append(Integer.toString(hours));
		strbuf.append(':');
		
		if (minutes < 10) {
			strbuf.append('0');			
		}
		strbuf.append(Integer.toString(minutes));
		strbuf.append(':');
		
		if (seconds < 10) {
			strbuf.append('0');			
		}
		strbuf.append(Integer.toString(seconds));
		
		strbuf.append('.');
		if (milliseconds < 100) {
			strbuf.append('0');			
		}
		if (milliseconds < 10) {
			strbuf.append('0');
		}
		strbuf.append(milliseconds);

		return strbuf.toString();
	}
	
	private void log(int level, String source, String message) {
		if (level > this.level) {
			return;
		}

		this.ps.print(timeToString(this.core.getTime()));
		this.ps.print(" " + levelToText(level));
		if (source != null) {
			this.ps.print(" [" + source + "]");
		}
		this.ps.print(": ");
		
		if (message != null) {
			this.ps.print(message);
		}
		this.ps.println();
		this.ps.flush();
	}

	/** 
	 * Logs a message with priority 'debug'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logDebug(String source, String message) {
		log(DEBUG, source, message);
	}
	
	/** 
	 * Logs a message with priority 'info'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logInfo(String source, String message) {
		log(INFO, source, message);		
	}
	
	/** 
	 * Logs a message with priority 'notice'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logNotice(String source, String message) {
		log(NOTICE, source, message);				
	}
	
	/** 
	 * Logs a message with priority 'warning'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logWarning(String source, String message) {
		log(WARNING, source, message);						
	}
	
	/** 
	 * Logs a message with priority 'error'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logError(String source, String message) {
		log(ERROR, source, message);						
	}
	
	/** 
	 * Logs a message with priority 'critical'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logCritical(String source, String message) {
		log(CRITICAL, source, message);						
	}
	
	/** 
	 * Logs a message with priority 'alert'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logAlert(String source, String message) {
		log(ALERT, source, message);						
	}
	
	/** 
	 * Logs a message with priority 'emergency'.
	 * 
	 * @param source logging source of this message.
	 * @param message message text to be logged.
	 */
	public void logEmergency(String source, String message) {
		log(EMERGENCY, source, message);						
	}

}
